package iss.java;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import iss.java.list.MyList;
import iss.java.list.Node;

/**
 * Created by wenke on 2016/9/16.
 */
public class Main_A {
    // TODO: Implement a multithreaded test case against requirement A.
    public static void main(String[] args) throws InterruptedException , BrokenBarrierException {
        MyList list = new MyList();


        Lock lock = new ReentrantLock();

        list.insert(list.getHead(), 5, lock);
        list.insert(list.getHead(), 4, lock);
        list.insert(list.getHead(), 3, lock);
        list.insert(list.getHead(), 2, lock);
        list.insert(list.getHead(), 1, lock);

        Node node=list.getHead().getNext().getNext();

        Thread w1=new Thread(new InDeData(node,1,lock));
        Thread w2=new Thread(new InDeData(node,-1,lock));
        Thread w3=new Thread(new InDeData(node,2,lock));
        Thread w4=new Thread(new InDeData(node,-2,lock));

        w1.start();
        w2.start();
        w3.start();
        w4.start();

        Thread.sleep(1000);
        System.out.println("线程结束，最终的运算结果为"+node.getData());
        if(node.getData()==2)
            System.out.println("ReentrantLock 互斥锁正常使用");
    }
}

class InDeData implements Runnable{
    private Node node;
    private int number;
    private Lock lock = new ReentrantLock();

    public InDeData(Node node, int number,Lock lock){
        this.node=node;
        this.number=number;
        this.lock=lock;
    }

    public void run(){
        lock.lock();
        try {
            for(int i=1;i<=10000000;i++) {
                node.setData(node.getData()+number);
            }
            System.out.println(Thread.currentThread().getName()+"数据更改完毕，更改后的数据为"+node.getData());
        }
        finally {
            lock.unlock();
        }

    }
}
